<?php
/**
 * Class Wallets
 * Desc  用户钱包Model
 * Create on 2021/8/26 8:59
 * Create by wangyafang
 */

namespace app\api\model\xyb;


class Wallets extends Base
{
    protected $name = 'xyb_wallets';

    public function getBalanceAttr($value, $data)
    {
        return bcsub($data['total_income'],$data['withdrawn_amount'],2);
    }

    public static function getWalletInfo($user_id, $type = 1)
    {
        return self::where('user_id',$user_id)->where('type',$type)->find();
    }

    public static function saveUsersWalletIncome($users_id, $type, $amount){
        if(!$wallet_info = self::getWalletInfo($users_id, $type)){
            return self::insert([
                'user_id'   => $users_id,
                'type'      => $type,
                'total_income'=>$amount,
                'can_withdrawal_amount'=>$amount
            ]);
        }
        $wallet_info->total_income = bcadd($wallet_info->total_income, $amount, 2);
        $wallet_info->can_withdrawal_amount = bcadd($wallet_info->can_withdrawal_amount, $amount, 2);
        $wallet_info->save();
        return $wallet_info;
    }

    public static function punishRider($users_id, $amount){
        return self::where('user_id',$users_id)
            ->where('can_withdrawal_amount','>=',$amount)
            ->where('type',2)
            ->setDec('can_withdrawal_amount', $amount);

    }
}